<template>
  <view id="myOrder" class="page">
    <view class="top">
      <text
        v-for="(item, index) in navTab"
        :key="index"
        @tap="currentTab(index)"
        :class="active == index ? 'top-active' : ''"
        >{{ item }}</text
      >
    </view>
    <!-- 未到店 -->
    <view v-if="active == 0" class="panel-box">
      <view v-if="orderListBefore.length > 0">
        <view
          class="item"
          v-for="(item, index) in orderListBefore"
          :key="index"
          @tap="onItemAppointment(item)"
        >
          <view class="title" @tap="onItemTapStore($event, item)">
            <view>
              <text class="name">{{
                item.community.name ? item.community.name : "--"
              }}</text>
              <image class="right" src="../../../image/right.png" />
            </view>
          </view>
          <view class="item-img">
            <image class="img-service" :src="imgUrl + item.service.url" />
            <text class="text-service">{{
              item.service.name ? item.service.name : "--"
            }}</text>
          </view>

          <view class="item-bottom">
            <view class="appointment">
              <view
                >预约时间 :
                {{ item.reservationTime ? item.reservationTime : "--" }}
              </view>
              <view class="box-car"
                >预约车辆 : {{ item.plateNo ? item.plateNo : "--" }}</view
              >
            </view>
            <view
              class="cancel-btn"
              v-if="item.status == 0"
              @tap="onItemCancel($event, item)"
              >取消预约</view
            >
          </view>
        </view>
      </view>

      <view v-else-if="orderListBefore.length == 0 && !isLoading" class="empty">
        <image src="../../../image/empty5.png" class="img" />
        <view class="empty-text">没有未到店的预约记录</view>
        <view class="empty-text2" @tap="onTapStore">立即预约</view>
      </view>
      <view v-if="!hasMore && orderListBefore.length > 0" class="no-more"
        >没有更多了</view
      >
    </view>
    <!-- 全部预约 -->
    <view v-if="active == 1" class="panel-box">
      <view v-if="orderListAll.length > 0">
        <view
          class="item"
          v-for="(item, index) in orderListAll"
          :key="index"
          @tap="onItemAppointment(item)"
        >
          <view class="title">
            <view @tap="onItemTapStore($event, item)">
              <text class="name">{{
                item.community.name ? item.community.name : "--"
              }}</text>
              <image class="right" src="../../../image/right.png" />
            </view>
            <text
              class="status"
              :style="{
                color:
                  item.status >= 0 && item.status <= 4
                    ? statusColors[item.status]
                    : statusColors[1],
              }"
              >{{ getStateDesc(item.status) }}</text
            >
          </view>
          <view class="item-img">
            <image class="img-service" :src="imgUrl + item.service.url" />
            <text class="text-service">{{
              item.service.name ? item.service.name : "--"
            }}</text>
          </view>

          <view class="item-bottom">
            <view class="appointment">
              <view
                >预约时间 :
                {{ item.reservationTime ? item.reservationTime : "--" }}
              </view>
              <view class="box-car"
                >预约车辆 : {{ item.plateNo ? item.plateNo : "--" }}</view
              >
            </view>
            <view
              class="cancel-btn"
              v-if="item.status == 0"
              @tap="onItemCancel($event, item)"
              >取消预约</view
            >
            <view
              class="cancel-btn"
              v-else-if="item.status == 1"
              @tap="onItemEvaluate($event, item)"
              >去评价</view
            >
          </view>
        </view>
      </view>

      <view v-else-if="orderListAll.length == 0 && !isLoading" class="empty">
        <image src="../../../image/empty5.png" class="img" />
        <view class="empty-text">没有未到店的预约记录</view>
        <view class="empty-text2" @tap="onTapStore">立即预约</view>
      </view>
      <view v-if="!hasMore && orderListAll.length > 0" class="no-more"
        >没有更多了</view
      >
    </view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./myOrder.less";
import { request } from "../../../util/axios.js";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
const API_CarCode = process.env.IOParking.API_CARCODE;
const apiBaseUrl = process.env.IOParking.API_HOST; //请求头部

const openIdMock = "oRPxj5bi2JB-id96cJ_s1wBWmjAo";
const mobileMock = "18039670989";
const common = require("../../../common.js");
import { isFastClick } from "../../../check.js";
export default {
  name: "myOrder",
  data() {
    return {
      navTab: ["未到店", "全部预约"],
      active: 0,
      orderListBefore: [],
      orderListAll: [],
      isLoading: true,
      paginations: {
        pageIndex: 1,
        pageSize: 15,
        total: 0,
      },
      hasMore: true,
      isFirstLoad: true,
      imgUrl: process.env.IOParking.IMAGE_BASE,
      statusColors: ["#08D4D2", "#3F3F3F", "#0DCC36", "#EB5757", "#909090"],
      showDialogCancel: false,
    };
  },
  components: {},
  mounted() {},

  onLoad: function (options) {
    wx.disableAlertBeforeUnload();
  },
  created() {},
  onShow() {
    try {
      var openId = Taro.getStorageSync("openId");
      if (!openId) {
        this.wx_login();
      } else {
        if (this.active == 0) {
          this.getOrderListBefore();
        } else {
          this.getOrderListAll();
        }
      }
    } catch (error) {
      this.wx_login();
    }
  },
  onPullDownRefresh() {
    this.paginations.pageIndex = 1;
    this.isFirstLoad = true;
    this.hasMore = true;
    if (this.active == 0) {
      this.getOrderListBefore();
    } else {
      this.getOrderListAll();
    }
    Taro.stopPullDownRefresh(); //结束刷新
  },
  onReachBottom() {
    //触发了上拉加载，做些什么
    this.paginations.pageIndex = this.paginations.pageIndex + 1;
    this.isFirstLoad = false;
    if (this.active == 0) {
      this.getOrderListBefore();
    } else {
      this.getOrderListAll();
    }
  },
  methods: {
    wx_login() {
      api
        .getUserInfo({
          scope: "all",
        })
        .then((resp) => {
          console.log("微信authCode is：", JSON.stringify(resp));
          if (resp.success) {
            if (resp.data == "mock") {
              Taro.setStorage({
                key: "openId",
                data: openIdMock,
              });
              Taro.setStorage({
                key: "mobile",
                data: mobileMock,
              });
              this.getOrderListBefore();
              return;
            }
            this.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getInfos(authCode) {
      Taro.request({
        url: apiBaseUrl + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          console.log("获取用户信息：", res.data);
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            let mobileRes = res.data.data.phoneNum;
            if (userOpenId) {
              Taro.setStorage({
                key: "openId",
                data: userOpenId,
              });
            }
            if (mobileRes) {
              Taro.setStorage({
                key: "mobile",
                data: mobileRes,
              });
            }
            this.paginations.pageIndex = 1;
            this.isFirstLoad = true;
            this.hasMore = true;
            if (this.active == 0) {
              this.getOrderListBefore();
            } else {
              this.getOrderListAll();
            }
          }
        },
      });
    },
    //回到主页
    goHome() {
      api.openPage("home");
    },
    goDetail() {},
    currentTab: function (e) {
      if (this.active == e) {
        return;
      }
      this.active = e;
      this.hasMore = true;
      this.loading = true;
      this.isFirstLoad = true;
      if (this.active == "0") {
        this.paginations.pageIndex = 1;
        this.getOrderListBefore();
      } else {
        this.paginations.pageIndex = 1;
        this.isLoading = true;
        this.getOrderListAll();
      }
    },

    getOrderListBefore() {
      if (!this.hasMore) {
        return;
      }
      Taro.showLoading({
        title: "加载中",
        mask: true,
      });
      Taro.request({
        url: API_CarCode + "reservationorder/pagelist",
        data: {
          pageIndex: this.paginations.pageIndex,
          pageSize: this.paginations.pageSize,
          filter: {
            openId: Taro.getStorageSync("openId"),
            status: 0,
          },
        },
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "POST",
        success: (res) => {
          Taro.hideLoading();
          this.isLoading = false;
          if (res.data.isSuccess) {
            this.paginations.total = res.data.data.total; //总数
            let list = res.data.data.list.map((item) => {
              item.reservationDate = common.formatTime(
                item.reservationDate.replace(/-/g, "/"),
                "Y-M-D"
              );
              item.reservationTime =
                item.reservationDate +
                " " +
                item.timeSlot.startTime +
                "-" +
                item.timeSlot.endTime;
              return item;
            });
            if (this.isFirstLoad) {
              //刷新的
              this.orderListBefore = list;
            } else {
              //上拉加载更多的
              this.orderListBefore = this.orderListBefore.concat(list);
            }
            if (list.length < this.paginations.pageSize) {
              this.hasMore = false;
            }
          }
        },
      });
    },
    getOrderListAll() {
      if (!this.hasMore) {
        return;
      }
      Taro.showLoading({
        title: "加载中",
        mask: true,
      });
      Taro.request({
        url: API_CarCode + "reservationorder/pagelist",
        data: {
          pageIndex: this.paginations.pageIndex,
          pageSize: this.paginations.pageSize,
          filter: {
            openId: Taro.getStorageSync("openId"),
            status: null,
          },
        },
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "POST",
        success: (res) => {
          Taro.hideLoading();
          this.isLoading = false;
          if (res.data.isSuccess) {
            this.paginations.total = res.data.data.total; //总数
            let list = res.data.data.list.map((item) => {
              item.reservationDate = common.formatTime(
                item.reservationDate.replace(/-/g, "/"),
                "Y-M-D"
              );
              item.reservationTime =
                item.reservationDate +
                " " +
                item.timeSlot.startTime +
                "-" +
                item.timeSlot.endTime;
              return item;
            });
            if (this.isFirstLoad) {
              //刷新的
              this.orderListAll = list;
            } else {
              //上拉加载更多的
              this.orderListAll = this.orderListAll.concat(list);
            }
            if (list.length < this.paginations.pageSize) {
              this.hasMore = false;
            }
          }
        },
      });
    },
    getStateDesc(status) {
      if (status == 0) {
        return "未到店";
      } else if (status == 1) {
        return "已完成";
      } else if (status == 2) {
        return "已评价";
      } else if (status == 3) {
        return "已过期";
      } else if (status == 4) {
        return "已取消";
      } else {
        return "";
      }
    },
    onTapStore() {
      if (isFastClick()) {
        return;
      }
      Taro.navigateTo({
        url: `../storeDetail/storeDetail?communityId=87163114566341`, //默认门店
      });
    },
    onItemTapStore(e, item) {
      if (isFastClick()) {
        return;
      }
      Taro.navigateTo({
        url: `../storeDetail/storeDetail?communityId=${item.communityId}`,
      });
      e.stopPropagation();
    },
    //取消预约
    onItemCancel(e, item) {
      if (isFastClick()) {
        return;
      }
      Taro.showModal({
        content: "确定取消本次预约吗？",
        confirmText: "确定取消",
        cancelText: "点错了",
        success: (res) => {
          if (res.confirm) {
            this.cancelOrder(item.id);
          } else if (res.cancel) {
            //取消
          }
        },
      });
      e.stopPropagation();
    },
    //立即评价
    onItemEvaluate(e, item) {
      if (isFastClick()) {
        return;
      }
      Taro.navigateTo({
        url: `../evaluate/evaluate?id=${item.id}`,
      });
      e.stopPropagation();
    },
    //预约记录
    onItemAppointment(item) {
      if (isFastClick()) {
        return;
      }
      Taro.navigateTo({
        url: `../appointmentDetail/appointmentDetail?id=${item.id}`,
      });
    },
    cancelOrder(id) {
      Taro.showLoading({
        title: "加载中",
        mask: true,
      });
      Taro.request({
        url:
          API_CarCode +
          "reservationorder/cancel?id=" +
          id +
          "&openId=" +
          Taro.getStorageSync("openId"),
        data: {},
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          Taro.hideLoading();
          if (res.data.isSuccess) {
            this.paginations.pageIndex = 1;
            Taro.showToast({
              title: "取消成功",
              icon: "success",
              duration: 1000,
              mask: true,
            });
            this.paginations.pageIndex = 1;
            this.isFirstLoad = true;
            this.hasMore = true;
            if (this.active == 0) {
              this.getOrderListBefore();
            } else if (this.active == 1) {
              this.getOrderListAll();
            }
          } else {
            Taro.showToast({
              title: res.data.message,
              icon: "error",
              duration: 1000,
              mask: true,
            });
          }
        },
      });
    },
    //page-end
  },
};
</script>

